import Mock from "mockjs";
const cartList = [];
const count = 47;

for (let i = 0; i < count; i++) {
    cartList.push( Mock.mock(
        {
            id: '@increment()',
            'img|1': ['https://img.alicdn.com/bao/uploaded/i1/478987173/O1CN01Oh0bTK22rHaSnwstv_!!478987173.jpg_80x80.jpg', 'https://i.loli.net/2018/07/13/5b48ac7766d98.png'],
            name: '@ctitle()',
            price:  '@float(1, 1000, 2, 2)',
            amount: '@integer(1, 5)',
        }
    ))
}

function getQueryVariable(url, name) {
    let index = url.indexOf('?');
    if(index != -1) {
        let queryParams = url.substring(index+1).split('&');
        for(let i = 0; i< queryParams.length; i++) {
            var params = queryParams[i].split("=");
            if(params[0] == name) {
                return params[1];
            }
        }
    }else {
        return null;
    }
}
Mock.mock(/\/cart\/getList/, 'get', (options) => {
    const page = getQueryVariable(options.url, "page");
    const limit = getQueryVariable(options.url, "limit");
    let start = (page-1) * limit;
    let end = page * limit;
    let res = cartList.slice(start, end);
    return {
        code: 200,
        msg: "数据获取成功",
        data: {
            total: cartList.length,
            data: res,
        }
    }
})

Mock.mock(/\/cart\/getByName/, 'get', (options) => {
    const name = decodeURI(getQueryVariable(options.url, "name"));
    var res = [];
    if( name != "")  {
        let list = cartList;
        list.forEach(e => {
            if(e.name == name) {
                let index = list.indexOf(e);
                if (index > -1) { 
                    res.push(e);
                } 
            }
        })     
    } else {
        res = cartList;
    }
    return {
        code: 200,
        msg: "成功",
        data: {
            total: res.length,
            data: res
        }
    }
})
/**
 * 有bug，需要修复
 */
Mock.mock(/\/cart\/deleteByIds/, 'post', (options) => {
    let idList = JSON.parse(options.body).ids;
    console.log(idList);
    let list = cartList;
    list.forEach( e => {
        let index = list.indexOf(e);
        if (index > -1) { 
            cartList.splice(index, 1);
        } 
    })
    return {
        code: 200,
        msg: "删除成功",
        data: null
    }
})

Mock.mock('/cart/save', 'post', (options) => {
    let body = JSON.parse(options.body);
    console.log(body);
    
})

Mock.mock(/\/cart\//, 'post', (options) => {
    let id = JSON.parse(options.body).id;
    console.log(id);
    let list = cartList;
    list.forEach( e => {
        if(e.id == id) {
            let index = list.indexOf(e);
            cartList.splice(index, 1);
        }
    })
    return {
        code: 200,
        msg: "删除成功",
        data: null
    }
})

export default Mock;